﻿using System;
using System.Collections.Generic;
using System.Data;
using Sok.Munkae.Core;
using Sok.Munkae.Core.DataInterfaces;
using Sok.Munkae.Tenant;

namespace Sok.Munkae.Data
{
    public class OrganizationRepository : IOrganizationRepository
        //notice that this repository doesn't inherit from IRepository<T>. It's special.
    {
        private int organizationId;
        private IDao<Organization> dao;
        private ITenantIdentifier tenantIdentifier;

        public OrganizationRepository(ITenantIdentifier tenantIdentifier,
                                      IDao<Organization> dao)
        {
            this.dao = dao;
            this.tenantIdentifier = tenantIdentifier;
            organizationId = tenantIdentifier.GetTenantId();
        }

        #region IOrganizationRepository Members

        public Organization Get()
        {
            return
                dao.GetOne(
                    "select Id,[Name],ShortName FROM Organization WHERE Id = @Id",
                    new Dictionary<string, object>() {{"@Id", organizationId}},
                    BuildOne);
        }
        
        public Organization Get(int organizationId)
        {
            return
                dao.GetOne(
                    "select Id,[Name],ShortName FROM Organization WHERE Id = @Id",
                    new Dictionary<string, object>() {{"@Id", organizationId}},
                    BuildOne);
        }

        public IList<Organization> GetAll()
        {
            throw new NotImplementedException();
        }

        #endregion

        //DEMO CODE QUALITY ALERT! Having this method in each repository is probably to repetitive, 
        // consider refactoring (DRY = "Don't Repeat Yourself")
        protected Organization BuildOne(IDataReader reader)
        {
            Organization org = new Organization();
            if (reader.Read())
            {
                org.Id = (int) reader["Id"];
                org.Name = (string) reader["Name"];
                org.ShortName = (string) reader["ShortName"];

                if (reader.Read())
                {
                    //too many results returned
                    org = null;
                }
            }
            return org;
        }
    }
}